from flask import Blueprint, redirect, url_for, flash, render_template
from BookWorldWeb.forms import LoginForm, RegisterForm
from BookWorldWeb.models import User, db

main_blueprint = Blueprint(
    'main',
    __name__,
    template_folder='../templates/main'
)


@main_blueprint.route('/')
def index():
    return redirect(url_for('blog.html'))


@main_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    """
    登录
    :return: 登录页
    """

    form = LoginForm()

    if form.validate_on_submit():
        flash('You have been logged in.', category='success')
        return redirect(url_for('blog.html'))

    return render_template('login.html', form=form)


@main_blueprint.route('/logout', methods=['GET', 'POST'])
def logout():
    """
    登出
    :return: 登录页
    """

    flash('You have been logged out.', category='success')
    return redirect(url_for('.home'))


@main_blueprint.route('/register', methods=['GET', 'POST'])
def register():
    """
    注册
    :return: 注册页
    """

    form = RegisterForm()

    if form.validate_on_submit():
        new_user = User()
        new_user.username = form.username.data
        new_user.set_password(form.password.data)

        db.session.add(new_user)
        db.session.commit()

        flash(
            'Your user has been created, please login.', category='success'
        )
        return redirect(url_for('.login'))

    return render_template('register.html', form=form)
